﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LandLordTheArtOfTheTradeIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LandLordTheArtOfTheTradeIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency LandLordTheArtOfTheTradeIssueFrequency = IssueBase.IssueFrequency.VeryCommon;
    private const float TargetDenarsConstant = 0.55f;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      if (!issueGiver.IsRuralNotable)
        return false;
      Village village = issueGiver.CurrentSettlement?.Village;
      return village != null && village.Bound.Town.GetItemPrice(village.VillageType.PrimaryProduction, (MobileParty) null, false) < village.VillageType.PrimaryProduction.Value;
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnSelected), typeof (LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssue), IssueBase.IssueFrequency.VeryCommon));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private IssueBase OnSelected(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssue(issueOwner, issueOwner.CurrentSettlement.Village.VillageType.PrimaryProduction);
    }

    public class LandLordTheArtOfTheTradeIssue : IssueBase
    {
      private const int IssueAndQuestDuration = 30;
      private const int CompanionRequiredSkillLevel = 120;
      private ItemObject _selectedItemObject;

      internal static void AutoGeneratedStaticCollectObjectsLandLordTheArtOfTheTradeIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get => IssueBase.AlternativeSolutionScaleFlag.Duration;
      }

      private int SelectedItemObjectCount
      {
        get
        {
          return MathF.Max(1, MathF.Round((float) (int) (5000.0 / (double) this._selectedItemObject.Value) * this.IssueDifficultyMultiplier));
        }
      }

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 2 + MathF.Ceiling(4f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 3 + MathF.Ceiling(5f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold
      {
        get
        {
          return (int) ((double) (this._selectedItemObject.Value * this.SelectedItemObjectCount) * (double) this.RewardGoldDeterministicRandomContribution);
        }
      }

      private float RewardGoldDeterministicRandomContribution
      {
        get
        {
          return this.IssueOwner.RandomFloatWithSeed((uint) this.IssueCreationTime.ElapsedDaysUntilNow, 0.2f, 0.5f);
        }
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject briefByIssueGiver = new TextObject("{=AKdDSZoM}Yes. It's a good problem to have, though. As you know, I deal in {.%}{SELECTED_ITEM}{.%}. Production this year has been very good, and we can no longer make a profit on the local market. I cannot however, put together a caravan to sell it elsewhere. So, I propose a very simple deal.[if:convo_innocent_smile][ib:confident]");
          if (this._selectedItemObject.HasHorseComponent || this._selectedItemObject.IsAnimal)
            briefByIssueGiver = new TextObject("{=llVFTH6n}Yes. It's a good problem to have, though. As you may know, I deal in {PLURAL(SELECTED_ITEM)}. Our herds have increased this year, and we can no longer make a profit on the local market. I cannot however organize a drive to a new market. So, I propose a very simple deal.[if:convo_innocent_smile][ib:confident]");
          briefByIssueGiver.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
          return briefByIssueGiver;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=8jyUn6mb}You sell me the goods at a discount?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=rWnvnufw}That could work, if you have the money. But if you don't, I'm willing to take a chance on you. I reckon for {SELECTED_ITEM_COUNT} {.%}{?SELECTED_ITEM_COUNT > 1}{PLURAL(SELECTED_ITEM)}{?}{SELECTED_ITEM}{\\?}{.%} you can probably find a market nearby where buyers will pay you a total of {TOTAL_GOLD}{GOLD_ICON}. Here's my offer. I loan you the product. You sell it at whatever price you like, and bring me back {TOTAL_GOLD}{GOLD_ICON} denars. I have little doubt you could find a market where you could get a better price than this, and make a profit.[if:convo_innocent_smile][ib:confident]");
          if (this._selectedItemObject.HasHorseComponent || this._selectedItemObject.IsAnimal)
            explanationByIssueGiver = new TextObject("{=b19Hlp7h}That could work, if you have the money. But if you don't, I'm willing to take a chance on you. I reckon for {SELECTED_ITEM_COUNT} {?SELECTED_ITEM_COUNT > 1}{PLURAL(SELECTED_ITEM)}{?}{SELECTED_ITEM}{\\?} you can probably find a market nearby where buyers will pay you a total of {TOTAL_GOLD}{GOLD_ICON}. Here's my offer. I loan you the livestock. You sell at whatever price you like, and bring me back {TOTAL_GOLD}{GOLD_ICON} denars. I have little doubt you could find a market where you could get a better price than this, and make a profit.[if:convo_innocent_smile][ib:confident]");
          explanationByIssueGiver.SetTextVariable("TOTAL_GOLD", (int) ((double) (this._selectedItemObject.Value * this.SelectedItemObjectCount) * 0.550000011920929));
          explanationByIssueGiver.SetTextVariable("SELECTED_ITEM_COUNT", this.SelectedItemObjectCount);
          explanationByIssueGiver.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
          explanationByIssueGiver.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssuePlayerResponseAfterAlternativeExplanation
      {
        get
        {
          return new TextObject("{=w1rVTUIs}This seems like a simple errand. Would your offer still stand if I get someone else to do it for me?");
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=PE97ZWvX}Not just anybody. If you have a companion that has your complete trust, then I'll agree... Just make sure he is well guarded. Goods attract bandits, as I'm sure you know. I suppose {ALTERNATIVE_TROOP_AMOUNT} well-armed men would be enough.[if:convo_innocent_smile][ib:confident]");
          explanationByIssueGiver.SetTextVariable("ALTERNATIVE_TROOP_AMOUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=aB0TT6Ur}Fear not. I will find the right market for your {.%}{SELECTED_ITEM}{.%} myself.");
          if (this._selectedItemObject.HasHorseComponent || this._selectedItemObject.IsAnimal)
            solutionAcceptByPlayer = new TextObject("{=cBO49V5b}Fear not. I will find the right market for your {PLURAL(SELECTED_ITEM)} myself.");
          solutionAcceptByPlayer.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=IFasMslv}I will assign a companion with {TROOP_COUNT} good men for {RETURN_DAYS} days.");
          solutionAcceptByPlayer.SetTextVariable("TROOP_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          solutionAcceptByPlayer.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=dLywF1Uz}I have heard your companion has started to sell the goods. This was a good deal, {?PLAYER.GENDER}ma'am{?}sir{\\?}.[if:convo_relaxed_happy][ib:confident]");
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          return new TextObject("{=aUXAh8cE}Very well, {PLAYER.NAME}. If you're willing to vouch for your companion, I'm sure this will work.[if:convo_innocent_smile][ib:confident]");
        }
      }

      public override bool IsThereAlternativeSolution => true;

      public override bool IsThereLordSolution => false;

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=BK9ww4NU}{QUEST_GIVER.LINK} asked you to sell {?QUEST_GIVER.GENDER}her{?}his{\\?} goods for at least {UNIT_PRICE}{GOLD_ICON} per {UNIT_NAME} and return to {?QUEST_GIVER.GENDER}her{?}him{\\?}. {?QUEST_GIVER.GENDER}She{?}He{\\?} told you that any profit that the deal would make above this price is yours to keep. You asked {COMPANION.LINK} to take {TROOP_COUNT} of your best men to go and take care of it. They should report back to you in {RETURN_DAYS} days.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent, true);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("UNIT_NAME", "{=g72xNv75}load");
          if (this._selectedItemObject.HasHorseComponent || this._selectedItemObject.IsAnimal)
            parent.SetTextVariable("UNIT_NAME", "{=T9Tgi9is}animal");
          parent.SetTextVariable("UNIT_PRICE", this._selectedItemObject.Value);
          parent.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          parent.SetTextVariable("TROOP_COUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=BDAmZkJF}You received a message from {ISSUE_GIVER.LINK}. 'It was a pleasure doing business with you and your folks.'");
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Title => new TextObject("{=96m29Eb7}The Art of The Trade");

      public override TextObject Description
      {
        get
        {
          TextObject description = new TextObject("{=BZwKEIm5}{ISSUE_GIVER.LINK} wants you to sell {?ISSUE_GIVER.GENDER}her{?}his{\\?} goods for a price above the global average.");
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject);
          return description;
        }
      }

      public LandLordTheArtOfTheTradeIssue(Hero issueOwner, ItemObject villageProduction)
        : base(issueOwner, CampaignTime.DaysFromNow(30f))
      {
        this._selectedItemObject = villageProduction;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.VillageHearth || issueEffect == DefaultIssueEffects.IssueOwnerPower ? -0.1f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Trade) >= hero.GetSkillValue(DefaultSkills.Riding) ? DefaultSkills.Trade : DefaultSkills.Riding, 120);
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        int solutionNeededMenCount = this.GetTotalAlternativeSolutionNeededMenCount();
        if (this.GetNumberOfTier2Troops(troopRoster) < solutionNeededMenCount)
        {
          explanation = new TextObject("{=rJIY7OiR}You have to send {NEEDED_TROOP_COUNT} troops with at least tier 2 to this quest.");
          explanation.SetTextVariable("NEEDED_TROOP_COUNT", solutionNeededMenCount);
          return false;
        }
        explanation = TextObject.Empty;
        return true;
      }

      private int GetNumberOfTier2Troops(TroopRoster troopRoster)
      {
        int numberOfTier2Troops = 0;
        foreach (TroopRosterElement troopRosterElement in (List<TroopRosterElement>) troopRoster.GetTroopRoster())
        {
          if (troopRosterElement.Character.Tier >= 2)
            numberOfTier2Troops += troopRoster.GetTroopCount(troopRosterElement.Character) - troopRoster.GetElementWoundedNumber(troopRoster.FindIndexOfTroop(troopRosterElement.Character));
        }
        return numberOfTier2Troops;
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      public override bool IssueStayAliveConditions()
      {
        return !this.IssueOwner.CurrentSettlement.IsRaided && !this.IssueOwner.CurrentSettlement.IsUnderRaid && (double) this.IssueOwner.CurrentSettlement.Village.Bound.Town.GetItemPrice(this.IssueOwner.CurrentSettlement.Village.VillageType.PrimaryProduction, (MobileParty) null, false) < (double) this.IssueOwner.CurrentSettlement.Village.VillageType.PrimaryProduction.Value * 1.2999999523162842;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        flags = IssueBase.PreconditionFlags.None;
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (FactionManager.IsAtWarAgainstFaction(issueGiver.MapFaction, Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        return flags == IssueBase.PreconditionFlags.None;
      }

      protected override void OnGameLoad()
      {
        this._selectedItemObject = this.IssueOwner.CurrentSettlement.Village.VillageType.PrimaryProduction;
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(30f), this._selectedItemObject, this.SelectedItemObjectCount);
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (900.0 + 800.0 * (double) this.IssueDifficultyMultiplier);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        GainRenownAction.Apply(Hero.MainHero, 1f);
        this.RelationshipChangeWithIssueOwner = 10;
      }
    }

    public class LandLordTheArtOfTheTradeIssueQuest : QuestBase
    {
      [SaveableField(10)]
      private ItemObject _selectedItemObject;
      [SaveableField(20)]
      private int _selectedItemObjectCount;
      [SaveableField(30)]
      private int _soldCount;
      [SaveableField(40)]
      private int _gatheredDenars;
      private bool _productsUndersold = true;
      [SaveableField(60)]
      private int _daysPassed;
      [SaveableField(70)]
      private bool _underSoldLogAdded;
      private int _targetDenarsToAchieve;
      [SaveableField(80)]
      private JournalLog _soldItemAmountLog;
      [SaveableField(90)]
      private JournalLog _gatheredDenarsLog;

      internal static void AutoGeneratedStaticCollectObjectsLandLordTheArtOfTheTradeIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._selectedItemObject);
        collectedObjects.Add((object) this._soldItemAmountLog);
        collectedObjects.Add((object) this._gatheredDenarsLog);
      }

      internal static object AutoGeneratedGetMemberValue_selectedItemObject(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._selectedItemObject;
      }

      internal static object AutoGeneratedGetMemberValue_selectedItemObjectCount(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._selectedItemObjectCount;
      }

      internal static object AutoGeneratedGetMemberValue_soldCount(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._soldCount;
      }

      internal static object AutoGeneratedGetMemberValue_gatheredDenars(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._gatheredDenars;
      }

      internal static object AutoGeneratedGetMemberValue_daysPassed(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._daysPassed;
      }

      internal static object AutoGeneratedGetMemberValue_underSoldLogAdded(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._underSoldLogAdded;
      }

      internal static object AutoGeneratedGetMemberValue_soldItemAmountLog(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._soldItemAmountLog;
      }

      internal static object AutoGeneratedGetMemberValue_gatheredDenarsLog(object o)
      {
        return (object) ((LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest) o)._gatheredDenarsLog;
      }

      public override TextObject Title => new TextObject("{=96m29Eb7}The Art of The Trade");

      public override bool IsRemainingTimeHidden => false;

      private bool QuestCanBeFinalized
      {
        get
        {
          if (Hero.OneToOneConversationHero == null || Hero.OneToOneConversationHero != this.QuestGiver)
            return false;
          if (this.ItemCountLeftToSell <= 0 || this._targetDenarsToAchieve <= this._gatheredDenars)
            return true;
          return this._daysPassed >= 1 && this.CheckIfPlayerLostItem();
        }
      }

      private int ItemCountLeftToSell => this._selectedItemObjectCount - this._soldCount;

      private int RemainingDenars => this._targetDenarsToAchieve - this._gatheredDenars;

      private TextObject QuestStartedLogText1
      {
        get
        {
          TextObject parent = new TextObject("{=2bcNCnI3}{QUEST_GIVER.LINK} asked you to sell {?QUEST_GIVER.GENDER}her{?}his{\\?} goods for at least {UNIT_PRICE}{GOLD_ICON} per load and return to {?QUEST_GIVER.GENDER}her{?}him{\\?}. {?QUEST_GIVER.GENDER}She{?}He{\\?} told you that any profit would make above this price is yours to keep.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent, true);
          parent.SetTextVariable("UNIT_PRICE", this._targetDenarsToAchieve / this._selectedItemObjectCount);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject QuestStartedLogText2
      {
        get
        {
          TextObject parent = new TextObject("{=jI251oj9}{?QUEST_GIVER.GENDER}She{?}He{\\?} noted that {?QUEST_GIVER.GENDER}she{?}he{\\?} has {SELECTED_ITEM_COUNT} {.%}{?SELECTED_ITEM_COUNT > 1}{PLURAL(SELECTED_ITEM)}{?}{SELECTED_ITEM}{\\?}{.%}. {?QUEST_GIVER.GENDER}She{?}He{\\?} is expecting to earn {TOTAL_GOLD}{GOLD_ICON} denars from that.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("SELECTED_ITEM_COUNT", this._selectedItemObjectCount);
          parent.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
          parent.SetTextVariable("TOTAL_GOLD", this._targetDenarsToAchieve);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject QuestStartedLogText3
      {
        get
        {
          TextObject parent = new TextObject("{=tf04Piaj}You told {?QUEST_GIVER.GENDER}her{?}him{\\?} that you will sell the goods personally.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestSuccessLogText
      {
        get
        {
          return new TextObject("{=EsNDadiR}You have completed your end of your bargain and made some denars simply by using your smarts.");
        }
      }

      private TextObject QuestReadyToBeFinishedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=2GMOnUIM}{QUEST_GIVER.LINK} expects your return to have {?QUEST_GIVER.GENDER}her{?}his{\\?} share of the deal.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          return parent;
        }
      }

      private TextObject QuestReadyToBeFinishedUnderSoldLogText
      {
        get
        {
          TextObject parent = new TextObject("{=IfPnl0B6}You have lost some of the wares you were supposed to be selling. You can speak with {QUEST_GIVER.LINK} to pay for a compensation.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestSuccessWithPayingGatheredDenarsLogText
      {
        get
        {
          TextObject parent = new TextObject("{=4bDHBIr1}You have completed your end of the bargain. {QUEST_GIVER.LINK} now considers you as a trustworthy {?PLAYER.GENDER}tradeswoman{?}tradesman{\\?}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          return parent;
        }
      }

      private TextObject QuestSuccessPlayerBoughtItemsLogText
      {
        get
        {
          TextObject parent = new TextObject("{=rYt43AWk}{QUEST_GIVER.LINK} accepted your offer to buy the products from an average price. You can now sell those for profits without any obligations to {?QUEST_GIVER.GENDER}her{?}him{\\?}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestFailedPlayerBrokeTheAgreementLogText
      {
        get
        {
          TextObject parent = new TextObject("{=1q2dxlol}You have failed to pay {TOTAL_DENAR}{GOLD_ICON} denars to {QUEST_GIVER.LINK}. {QUEST_GIVER_VILLAGE} and its locals are aware of your misdemeanor.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_VILLAGE", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("TOTAL_DENAR", this._targetDenarsToAchieve);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject QuestCanceledWarDeclaredLog
      {
        get
        {
          TextObject parent = new TextObject("{=vW6kBki9}Your clan is now at war with {QUEST_GIVER.LINK}'s realm. Your agreement with {QUEST_GIVER.LINK} is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestGiverVillageRaided
      {
        get
        {
          TextObject parent = new TextObject("{=w0FD9U98}{QUEST_GIVER.LINK}'s village is raided. Your agreement with {?QUEST_GIVER.GENDER}her{?}him{\\?} is moot.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_SETTLEMENT", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject QuestFailedWithTimeOutLogText
      {
        get
        {
          TextObject parent = new TextObject("{=PQt8lfTX}You have failed to return to the {QUEST_GIVER.LINK} in time. {QUEST_GIVER_VILLAGE} and its locals are aware of your misdemeanor.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_VILLAGE", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      public LandLordTheArtOfTheTradeIssueQuest(
        string questId,
        Hero giverHero,
        CampaignTime duration,
        ItemObject selectedItemObject,
        int selectedItemObjectCount)
        : base(questId, giverHero, duration, 0)
      {
        this._selectedItemObject = selectedItemObject;
        this._selectedItemObjectCount = selectedItemObjectCount;
        this._targetDenarsToAchieve = (int) ((double) (selectedItemObject.Value * selectedItemObjectCount) * 0.550000011920929);
        this._daysPassed = 0;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void SetDialogs()
      {
        TextObject text1 = new TextObject("{=3Sk0BQ4n}I will buy the products from you for {TOTAL_GOLD}{GOLD_ICON}. This way we both will get what we desire.");
        if (this._selectedItemObject.IsAnimal || this._selectedItemObject.HasHorseComponent)
          text1 = new TextObject("{=7nBOWsg2}I will buy the livestock from you for {TOTAL_GOLD}{GOLD_ICON}. This way we both will get what we desire.");
        text1.SetTextVariable("TOTAL_GOLD", this._targetDenarsToAchieve);
        text1.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        TextObject text2 = new TextObject("{=iYtzlRSN}I would rather be your middleman on this matter. I need to keep my money. You can have your men load up the {.%}{SELECTED_ITEM}{.%} already.");
        if (this._selectedItemObject.IsAnimal || this._selectedItemObject.HasHorseComponent)
          text2 = new TextObject("{=exmSGWUb}I would rather be your middleman on this matter. I need to keep my money. You can have your men get the herd ready.");
        text2.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        TextObject npcText1 = new TextObject("{=9d6WxRrj}Do you want to buy the goods yourself? Or will I retain ownership, and you just keep the extra profits? I am expecting to earn {TOTAL_DENARS}{GOLD_ICON} for {SELECTED_COUNT} loads of produce. If would like to buy it right away you can simply sell it yourself or do whatever you wish with it.");
        if (this._selectedItemObject.IsAnimal || this._selectedItemObject.HasHorseComponent)
          npcText1 = new TextObject("{=GihVcxIB}Do you want to buy the livestock yourself? Or will I retain ownership, and you just keep the extra profits? I am expecting to earn {TOTAL_DENARS}{GOLD_ICON} in total. If would like to buy the livestock right away you can simply sell it yourself or do whatever you wish with it.");
        npcText1.SetTextVariable("TOTAL_DENARS", this._targetDenarsToAchieve);
        npcText1.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        npcText1.SetTextVariable("SELECTED_COUNT", this._selectedItemObjectCount);
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=NaoYCmC6}Good. Needless to say, by not taking any money up front, I am trusting in your honesty in your ability to protect those goods. But I am sure that trust will not be misplaced.[if:convo_innocent_smile][ib:closed]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).NpcLine(npcText1).BeginPlayerOptions().PlayerOption(text1).ClickableCondition(new ConversationSentence.OnClickableConditionDelegate(this.PlayerBuyClickableOptionCondition)).NpcLine(new TextObject("{=LmTii9E2}It was a pleasure doing business with you. If only everyone was as honest as you.[if:convo_happy][ib:confident3]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          this.StartQuest();
          this.QuestFinishedPlayerBoughtTheGoods();
        })).CloseDialog().PlayerOption(text2).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog().EndPlayerOptions().CloseDialog();
        TextObject playerMainOptionOneWithGold = new TextObject("{=1zdkXAwL}The market isn't what we expected. I am afraid I only made {GATHERED_DENARS}{GOLD_ICON} of the {TOTAL_DENARS}{GOLD_ICON} that we agreed upon.");
        playerMainOptionOneWithGold.SetTextVariable("GATHERED_DENARS", this._gatheredDenars);
        playerMainOptionOneWithGold.SetTextVariable("TOTAL_DENARS", this._targetDenarsToAchieve);
        playerMainOptionOneWithGold.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        TextObject playerMainOptionOneNoGold = new TextObject("{=52lNazA1}I'm afraid that things came up. I was not able to make the sale.");
        TextObject text3 = new TextObject("{=!}{PLAYER_OPTION}");
        TextObject text4 = new TextObject("{=THD3C7xc}I have. Here is the {TOTAL_DENARS}{GOLD_ICON} denars just as we agreed.[ib:hip2]");
        text4.SetTextVariable("TOTAL_DENARS", this._targetDenarsToAchieve);
        text4.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        TextObject text5 = new TextObject("{=z47GjqTZ}Yes, of course. This is the {TOTAL_DENARS}{GOLD_ICON} denars that I owe you.[ib:hip2]");
        text5.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        text5.SetTextVariable("TOTAL_DENARS", this._targetDenarsToAchieve);
        TextObject playerFailOptionWithGold = new TextObject("{=dtzKfkrh}We never agreed on this. I am not paying you any more than {GATHERED_DENARS}{GOLD_ICON}, and you cannot force me.");
        playerFailOptionWithGold.SetTextVariable("GATHERED_DENARS", this._gatheredDenars);
        TextObject playerFailOptionNoGold = new TextObject("{=aFDiKxhr}Our deal involved you getting your cut from the sales I made. No sale means no cut. I'm sure you understand.[ib:warrior2]");
        TextObject text6 = new TextObject("{=!}{PLAYER_FAIL_OPTION}");
        TextObject npcText2 = new TextObject("{=41wb8QaV}I know I can not force you to pay you what you owe me. But I think you will find that a good name is worth more than a few loads of {SELECTED_ITEM}...");
        npcText2.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        if (this._selectedItemObject.IsAnimal || this._selectedItemObject.HasHorseComponent)
          npcText2 = new TextObject("{=pcrdOlE8}I know I can not force you to pay you what you owe me. But I think you will find that a good name is worth more than a bit of livestock...");
        TextObject textObject1 = new TextObject("{=OIwtLKN3}I am a {?PLAYER.GENDER}woman{?}man{\\?} of my word. I will raise some money to pay you. Wait for my return {QUEST_GIVER.LINK}.");
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject1);
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject textObject2 = new TextObject("{=bPPXiybO}I just happened to be around. Have no fear {QUEST_GIVER.NAME}, your goods are fine.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject2);
        TextObject npcText3 = new TextObject("{=ekSg8okD}I will be better once you return with the denars you owe me {PLAYER.NAME}.[ib:aggressive2]");
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject2);
        TextObject text7 = new TextObject("{=bbsN6hOo}Have you already sold that {SELECTED_ITEM}? If so, that seems awfully quick.");
        text7.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").BeginNpcOptions().NpcOption(text7, (ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero != null && Hero.OneToOneConversationHero == this.QuestGiver && !this.QuestCanBeFinalized)).BeginPlayerOptions().PlayerOption(new TextObject("{=gVad94Br}I was just checking in with you.")).Condition((ConversationSentence.OnConditionDelegate) (() => !this.QuestCanBeFinalized)).NpcLine(npcText3).CloseDialog().PlayerOption(textObject2).Condition((ConversationSentence.OnConditionDelegate) (() => !this.QuestCanBeFinalized)).NpcLine(npcText3).CloseDialog().EndPlayerOptions().NpcOption(new TextObject("{=1q3FKY1s}Have you made your trip yet? I presume you were able to make a sale?"), (ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero != null && Hero.OneToOneConversationHero == this.QuestGiver && this.QuestCanBeFinalized)).BeginPlayerOptions().PlayerOption(text3).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          if (this._gatheredDenars > 0)
          {
            playerMainOptionOneWithGold.SetTextVariable("GATHERED_DENARS", this._gatheredDenars);
            Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("PLAYER_OPTION", playerMainOptionOneWithGold);
          }
          else
            Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("PLAYER_OPTION", playerMainOptionOneNoGold);
          return this.QuestCanBeFinalized && this._productsUndersold;
        })).NpcLine(new TextObject("{=QlYUE00L}Well. We did have an agreement. I do expect you to pay the full amount.")).BeginPlayerOptions().PlayerOption(text5).ClickableCondition(new ConversationSentence.OnClickableConditionDelegate(this.PlayerPayAgreedDenarsClickableCondition)).NpcLine(new TextObject("{=gNHh9bvb}I am sorry that you did not manage to make a profit. But you are keeping your end of the bargain, and that is admirable.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.PlayerPaidAgreedDenarsQuestSuccess))).CloseDialog().PlayerOption(text6).ClickableCondition(new ConversationSentence.OnClickableConditionDelegate(this.PlayerFailWithGoldClickableCondition)).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          if (this._gatheredDenars > 0)
          {
            playerFailOptionWithGold.SetTextVariable("GATHERED_DENARS", this._gatheredDenars);
            Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("PLAYER_FAIL_OPTION", playerFailOptionWithGold);
          }
          else
            Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("PLAYER_FAIL_OPTION", playerFailOptionNoGold);
          return true;
        })).NpcLine(npcText2).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.QuestFailedPlayerBrokeTheAgreement))).CloseDialog().PlayerOption(textObject1).NpcLine(new TextObject("{=RxjuaDum}I am glad of that. Don't make me wait too long. Some men say they will pay a debt, and you never see them again.[if:convo_mocking_teasing][ib:confident2]")).CloseDialog().EndPlayerOptions().PlayerOption(text4).Condition((ConversationSentence.OnConditionDelegate) (() => this.QuestCanBeFinalized && !this._productsUndersold)).NpcLine(new TextObject("{=9jFqXvHy}Excellent! I knew you were an honest soul. Trust is a fine thing, isn't it? Perhaps we can do more business in the future.[if:convo_innocent_smile][ib:confident]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestSuccessPlayerSoldTheProducts)).CloseDialog().EndPlayerOptions().EndNpcOptions();
      }

      private void QuestSuccessPlayerSoldTheProducts()
      {
        this.AddLog(this.QuestSuccessLogText);
        GainRenownAction.Apply(Hero.MainHero, 1f);
        this.RelationshipChangeWithQuestGiver = 10;
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, this.QuestGiver, this._targetDenarsToAchieve);
        this.CompleteQuestWithSuccess();
      }

      private void QuestFailedPlayerBrokeTheAgreement()
      {
        this.AddLog(this.QuestFailedPlayerBrokeTheAgreementLogText);
        ChangeCrimeRatingAction.Apply(this.QuestGiver.MapFaction, 5f);
        this.QuestGiver.AddPower(-5f);
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, this.QuestGiver, this._gatheredDenars);
        this.RelationshipChangeWithQuestGiver = -10 - this.RemainingDenars / 10;
        this.CompleteQuestWithFail();
      }

      private void PlayerPaidAgreedDenarsQuestSuccess()
      {
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, this.QuestGiver, this._targetDenarsToAchieve);
        this.RelationshipChangeWithQuestGiver = 10;
        GainRenownAction.Apply(Hero.MainHero, 1f);
        this.AddLog(this.QuestSuccessWithPayingGatheredDenarsLogText);
        this.CompleteQuestWithSuccess();
      }

      private bool PlayerPayAgreedDenarsClickableCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        if (Hero.MainHero.Gold < this._targetDenarsToAchieve)
        {
          explanation = new TextObject("{=d0kbtGYn}You don't have enough gold.");
          return false;
        }
        MBTextManager.SetTextVariable("REMAINING_DENARS", this.RemainingDenars);
        return true;
      }

      private bool PlayerFailWithGoldClickableCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        if (this._gatheredDenars <= 0 || Hero.MainHero.Gold >= this._gatheredDenars)
          return true;
        explanation = new TextObject("{=d0kbtGYn}You don't have enough gold.");
        return false;
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddTrackedObject((ITrackableCampaignObject) this.QuestGiver.CurrentSettlement);
        MobileParty.MainParty.ItemRoster.AddToCounts(this._selectedItemObject, this._selectedItemObjectCount);
        TextObject message = new TextObject("{=jKHkGzUn}As agreed, {SELECTED_ITEM_COUNT} {?IS_PLURAL}{.%}{PLURAL(SELECTED_ITEM)}{.%} have been{?}{.%}{SELECTED_ITEM}{.%} has been{\\?} added to your inventory.");
        message.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        message.SetTextVariable("SELECTED_ITEM_COUNT", this._selectedItemObjectCount);
        message.SetTextVariable("IS_PLURAL", this._selectedItemObjectCount > 1 ? 1 : 0);
        MBInformationManager.AddQuickInformation(message);
        this.AddLog(this.QuestStartedLogText1);
        this.AddLog(this.QuestStartedLogText2);
        this.AddLog(this.QuestStartedLogText3);
        TextObject taskName1 = new TextObject("{=GaXEmoFy}Sold {.%}{SELECTED_ITEM}{.%} amount:");
        taskName1.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        TextObject taskName2 = new TextObject("{=pwnqk0Nj}Gathered denars from {.%}{SELECTED_ITEM}{.%}");
        taskName2.SetTextVariable("SELECTED_ITEM", this._selectedItemObject.Name);
        this._soldItemAmountLog = this.AddDiscreteLog(TextObject.Empty, taskName1, this._soldCount, this._selectedItemObjectCount);
        this._gatheredDenarsLog = this.AddDiscreteLog(TextObject.Empty, taskName2, this._gatheredDenars, this._targetDenarsToAchieve);
      }

      private void QuestFinishedPlayerBoughtTheGoods()
      {
        this.AddLog(this.QuestSuccessPlayerBoughtItemsLogText);
        MobileParty.MainParty.ItemRoster.AddToCounts(this._selectedItemObject, this._selectedItemObjectCount);
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, this.QuestGiver, this._targetDenarsToAchieve);
        GainRenownAction.Apply(Hero.MainHero, 1f);
        this.RelationshipChangeWithQuestGiver = 1;
        this.CompleteQuestWithSuccess();
      }

      private bool PlayerBuyClickableOptionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        if (Hero.MainHero.Gold >= this._targetDenarsToAchieve)
          return true;
        explanation = new TextObject("{=d0kbtGYn}You don't have enough gold.");
        return false;
      }

      protected override void OnTimedOut()
      {
        this.AddLog(this.QuestFailedWithTimeOutLogText);
        this.RelationshipChangeWithQuestGiver = -10;
        ChangeCrimeRatingAction.Apply(this.QuestGiver.MapFaction, 5f);
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.VillageBeingRaided.AddNonSerializedListener((object) this, new Action<Village>(this.OnVillageRaided));
        CampaignEvents.PlayerInventoryExchangeEvent.AddNonSerializedListener((object) this, new Action<List<(ItemRosterElement, int)>, List<(ItemRosterElement, int)>, bool>(this.OnPlayerInventoryExchange));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      protected override void HourlyTick()
      {
        if (!this.IsOngoing || this._underSoldLogAdded || !this.CheckIfPlayerLostItem())
          return;
        this.AddLog(this.QuestReadyToBeFinishedUnderSoldLogText);
        ++this._daysPassed;
        this._underSoldLogAdded = true;
      }

      private bool CheckIfPlayerLostItem()
      {
        return this._soldCount + MobileParty.MainParty.ItemRoster.GetItemNumber(this._selectedItemObject) < this._selectedItemObjectCount;
      }

      private void OnPlayerInventoryExchange(
        List<(ItemRosterElement, int)> purchasedItems,
        List<(ItemRosterElement, int)> soldItems,
        bool isTrading)
      {
        if (!isTrading || this.ItemCountLeftToSell <= 0)
          return;
        foreach ((ItemRosterElement, int) soldItem in soldItems)
        {
          if (soldItem.Item1.EquipmentElement.Item == this._selectedItemObject)
          {
            this._soldCount += soldItem.Item1.Amount;
            this._gatheredDenars += soldItem.Item2;
          }
        }
        if (this.ItemCountLeftToSell <= 0)
          this.AddLog(this.QuestReadyToBeFinishedLogText);
        this._productsUndersold = this._gatheredDenars < this._targetDenarsToAchieve;
        this._soldItemAmountLog.UpdateCurrentProgress(this._soldCount);
        this._gatheredDenarsLog.UpdateCurrentProgress(this._gatheredDenars);
      }

      private void OnVillageRaided(Village village)
      {
        if (village != this.QuestGiver.CurrentSettlement.Village)
          return;
        this.AddLog(this.QuestGiverVillageRaided);
        this.CompleteQuestWithCancel();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.CurrentSettlement.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this.QuestCanceledWarDeclaredLog);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this.PlayerDeclaredWarQuestLogText, this.QuestCanceledWarDeclaredLog);
      }

      protected override void OnFinalize()
      {
      }

      protected override void InitializeQuestOnGameLoad()
      {
        this._targetDenarsToAchieve = (int) ((double) (this._selectedItemObject.Value * this._selectedItemObjectCount) * 0.550000011920929);
        this._productsUndersold = this._gatheredDenars < this._targetDenarsToAchieve;
        this.SetDialogs();
      }
    }

    public class LandLordTheArtOfTheTradeIssueBehaviorTypeDefiner : SaveableTypeDefiner
    {
      public LandLordTheArtOfTheTradeIssueBehaviorTypeDefiner()
        : base(249000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssue), 1);
        this.AddClassDefinition(typeof (LandLordTheArtOfTheTradeIssueBehavior.LandLordTheArtOfTheTradeIssueQuest), 2);
      }
    }
  }
}
